//
//  catchViewController.m
//  HelloWordPrimer
//
//  Created by erik on 2009-10-30.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "catchViewController.h"
#import "FishMapViewController.h"
#import "Catch.h"
#import "CatchPhoto.h"

#define kViewTag				1


@implementation catchViewController

@synthesize navController;
@synthesize actionSheet;
@synthesize weight;
@synthesize speciesValue;
@synthesize managedObjectContext;
@synthesize location;
@synthesize pickerView;
@synthesize source;
@synthesize currentPhoto;
@synthesize mapView;

static NSString *kSectionTitleKey = @"sectionTitleKey";
static NSString *kRowTitleKey = @"rowKey";
static NSString *kSubTitleKey = @"subRowKey";
static NSString *kSourceKey = @"sourceKey";


- (void)viewDidLoad {
    [super viewDidLoad];
	
	[self setTitle:@"New Catch"];
	UIBarButtonItem *doneButton = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(saveCatch:)];
	doneButton.style = UIBarButtonItemStyleDone;
	self.navigationItem.rightBarButtonItem = doneButton;
	self.speciesValue = @"none";
	//[[UIDevice currentDevice]setOrientation:UIInterfaceOrientationPortrait];
	[doneButton release];
	
	self.source = [NSMutableArray arrayWithObjects:				   
				   
				   [NSMutableDictionary dictionaryWithObjectsAndKeys:
					@"Photo", kSectionTitleKey,
					@"Tap to add a photo", kRowTitleKey,
					@"Current photo: none", kSubTitleKey,
					@"photo",kSourceKey,
					//skicka me kontrollen som ska användas...self.switchCtl, kViewKey,
					nil],
				   
				   [NSMutableDictionary dictionaryWithObjectsAndKeys:
					@"Species", kSectionTitleKey,
					@"Tap to set species", kRowTitleKey,
					@"Current Species: none", kSubTitleKey,
					@"species",kSourceKey,
					//skicka me kontrollen som ska användas...self.switchCtl, kViewKey,
					nil],
				   
				   [NSMutableDictionary dictionaryWithObjectsAndKeys:
					@"Weight", kSectionTitleKey,
					@"Tap to set weight", kRowTitleKey,
					@"Current weight: 0.0 Kg", kSubTitleKey,
					@"weight",kSourceKey,
					//skicka me kontrollen som ska användas...self.switchCtl, kViewKey,
					nil],
				   
				   nil];	
}

-(void)saveCatch:(id)sender{
	//spara all info här....	
	if(managedObjectContext)
	{
		if (!location) {
			NSLog(@"No location provided");
			return;
		}

		// Persistence test
		Catch *catch = (Catch *) [NSEntityDescription insertNewObjectForEntityForName:@"Catch" inManagedObjectContext:managedObjectContext];
		CLLocationCoordinate2D coordinate = [location coordinate]; // Get coordinates from current location
		catch.longitude = [NSNumber numberWithDouble:coordinate.longitude];
		catch.latitude = [NSNumber numberWithDouble:coordinate.latitude];

		NSFetchRequest *request = [[NSFetchRequest alloc] init];
		NSEntityDescription *entity = [NSEntityDescription entityForName:@"Catch" inManagedObjectContext:managedObjectContext];
		[request setEntity:entity];
		
		// Execute the fetch -- create a mutable copy of the result.
		NSError *aError = nil;
		NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&aError] mutableCopy];
		
		int nrOfCatches = [mutableFetchResults count];
		
		NSLog([[NSString alloc]initWithFormat:@"nr  of catches: %d",nrOfCatches]);
		
		catch.catchID = [[NSNumber alloc]initWithInteger:nrOfCatches];
		catch.catchDate = [NSDate date];
		catch.species = [self speciesValue];
		catch.weight = [NSNumber numberWithDouble:[self.weight doubleValue]];

		// Add annotation
		FishCatchAnnotation *catchAnno = [[FishCatchAnnotation alloc] initWithCoordinate:coordinate];
		[catchAnno setTitle:speciesValue];
		[catchAnno setSubtitle:[[NSString alloc]initWithFormat:@"%@ Kg",weight]];
		
		[catchAnno setSourceID:catch.catchID];
		
		NSLog([[NSString alloc]initWithFormat:@"catchID: %d",[catch.catchID intValue]]);
		NSLog([[NSString alloc]initWithFormat:@"sourceID: %d",[catchAnno.sourceID intValue]]);
		
		CatchPhoto *catchPhoto = (CatchPhoto *) [NSEntityDescription insertNewObjectForEntityForName:@"CatchPhoto" inManagedObjectContext:managedObjectContext];		

		if(currentPhoto){
			NSData *imgData = UIImagePNGRepresentation(self.currentPhoto);
			[catchPhoto setData:imgData];
			//[catch set];
			NSLog(@"sätter imgData");
		}
		else{
			NSLog(@"inget foto vid init");
			catchPhoto.data = nil;
		}
		//knyta dessa.
		[catch setPhoto: catchPhoto];
		[catchPhoto setParent:catch];

		
		[self.mapView addAnnotation:catchAnno];
		NSLog(@"Try to save one catch at current location");
		NSError *error;
		if (![managedObjectContext save:&error]) {
			NSLog(@"Ett fel uppstod!!");
			UIAlertView *theError = [[UIAlertView alloc] initWithTitle: @"Save error"
															   message: @"Error saving data to persisten store"
															  delegate: self cancelButtonTitle: @"Ok"
													 otherButtonTitles: nil];
			NSLog([error description]);
			[theError show];
			[theError release];
		}
		[self.navigationController popViewControllerAnimated:YES];
	}
	else{
		UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"No context" message:@"No context available" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
		[alert release];
	}	
}

-(void)changeSpecies:(NSString *)species{
	self.speciesValue = species;
	NSString *newValue = [[NSString alloc]initWithFormat:@"Current Species: %@",self.speciesValue];
	
	NSMutableDictionary * newObject = [NSMutableDictionary dictionaryWithObjectsAndKeys:
									   @"Species", kSectionTitleKey,
									   @"Tap to set species", kRowTitleKey,
									   newValue, kSubTitleKey,
									   @"species",kSourceKey,
									   //skicka me kontrollen som ska användas...self.switchCtl, kViewKey,
									   nil];
	
	[source replaceObjectAtIndex:1 withObject:newObject];
	[source didChangeValueForKey:kSubTitleKey];
	[self.tableView reloadData];
	NSLog(@"ändrar");
}

-(void)changeWeight:(NSString *)theWeight{
	self.weight = theWeight;
	NSString *newValue = [[NSString alloc]initWithFormat:@"Current Weight: %@ Kg",self.weight];
	NSMutableDictionary * newObject = [NSMutableDictionary dictionaryWithObjectsAndKeys:
	 @"Weight", kSectionTitleKey,
	 @"Tap to set weight", kRowTitleKey,
	 newValue, kSubTitleKey,
	 @"weight",kSourceKey,
	 //skicka me kontrollen som ska användas...self.switchCtl, kViewKey,
	 nil];
	
	[source replaceObjectAtIndex:2 withObject:newObject];
	[source didChangeValueForKey:kSubTitleKey];
	[self.tableView reloadData];
}

#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	return [self.source count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	return [[self.source objectAtIndex: section] valueForKey:kSectionTitleKey];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return 2;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	static NSString *CellIdentifier = @"SourceCellID";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
	}
	else
	{
		// the cell is being recycled, remove old embedded controls
		UIView *viewToRemove = nil;
		viewToRemove = [cell.contentView viewWithTag:kViewTag];
		if (viewToRemove)
			[viewToRemove removeFromSuperview];
	}
	
	if([indexPath row] == 0){
		cell.textLabel.highlightedTextColor = [UIColor blackColor];
		cell.textLabel.font = [UIFont systemFontOfSize:16];	
		cell.textLabel.text = [[self.source objectAtIndex: indexPath.section] valueForKey:kRowTitleKey];
		
		//UIControl *control = [[self.source objectAtIndex: indexPath.section] valueForKey:kViewKey];
		//[cell.contentView addSubview:control];
	}
	else{
		cell.textLabel.opaque = NO;
		cell.textLabel.textAlignment = UITextAlignmentCenter;
		cell.textLabel.textColor = [UIColor grayColor];
		cell.textLabel.numberOfLines = 2;
		cell.textLabel.highlightedTextColor = [UIColor blackColor];
		cell.textLabel.font = [UIFont systemFontOfSize:12];	
		cell.textLabel.text = [[self.source objectAtIndex: indexPath.section] valueForKey:kSubTitleKey];
	}
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	NSMutableDictionary * di = [source objectAtIndex:indexPath.section];
	NSLog([di valueForKey:kSourceKey]);
	NSString *caller = [di valueForKey:kSourceKey];
	
	if(caller == @"photo"){
		[self takePhoto];
	}
	
	else if(caller == @"species"){
		[self setSpecies];
	}
	
	else if(caller == @"weight"){
		[self setWeightValue];
	}
}

-(void)setWeightValue{
	
	UIActionSheet *speciesSheet = [[UIActionSheet alloc] initWithTitle:@"Weight"
															  delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil
													 otherButtonTitles:@"Dummy",@"Dummy",@"Dummy",@"Dummy", nil];
	[self setActionSheet:speciesSheet];
	
	speciesSheet.actionSheetStyle = UIActionSheetStyleDefault;
	WeightPickerController *weightPickerView = [[WeightPickerController alloc]initWithNibName:@"WeightPickerView" bundle:nil];
	
	[weightPickerView setActionSheet:speciesSheet];
	[speciesSheet addSubview:weightPickerView.view];      
	[speciesSheet showInView:self.view]; 	
	
	[speciesSheet release];
	[(WeightPickerController *)weightPickerView setParent:self];
}

-(void)setSpecies{
	
	UIActionSheet *speciesSheet = [[UIActionSheet alloc] initWithTitle:@"Species"
															  delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil
													 otherButtonTitles:@"Dummy",@"Dummy",@"Dummy",@"Dummy", nil];
	[self setActionSheet:speciesSheet];
	
	speciesSheet.actionSheetStyle = UIActionSheetStyleDefault;
	SpeciesPickerViewController *picker = [[SpeciesPickerViewController alloc]initWithNibName:@"SpeciesPickerView" bundle:nil];
	
	[picker setActionSheet:speciesSheet];
	[speciesSheet addSubview:picker.view];      
	[speciesSheet showInView:self.view]; 	
	
	[speciesSheet release];
	[picker setParent:self];
	//får inte släppa denna av någon anledning...
	//[pickerView release];
}

-(void)takePhoto{
	if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
		UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
		imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
		imagePicker.delegate = self;
		[self presentModalViewController:imagePicker animated:YES];
		[imagePicker release];
	}
	else if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
		UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
		//använd UIImagePickerControllerSourceTypeSavedPhotosAlbum eller UIImagePickerControllerSourceTypeCamera
		//på devicen!!
		imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
		imagePicker.delegate = self;
		[self presentModalViewController:imagePicker animated:YES];
		[imagePicker release];
	}
}

- (void)imagePickerController:(UIImagePickerController *)picker 
				didFinishPickingMediaWithInfo:(NSDictionary *)info{

	UIImage *image = (UIImage *)[info objectForKey:UIImagePickerControllerOriginalImage];	
	//NSLog([[NSString alloc]initWithFormat:@"%@", [info objectForKey:UIImagePickerControllerMediaType]]);
	
	[self useImage:image];
	[[picker parentViewController] dismissModalViewControllerAnimated:YES];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{	
	[[picker parentViewController]dismissModalViewControllerAnimated:YES];
}

-(void)useImage:(UIImage *)usedImage{
	self.currentPhoto = usedImage;
}

- (void)viewWillDisappear:(BOOL)animated{
	
	NSString *sourceController = [navController topViewController].nibName;
	if([sourceController isEqual:@"FishMapViewController"]){
		[[self navController] setToolbarHidden:NO animated:YES];
		[[self navController] setNavigationBarHidden:YES animated:YES];
	}
}

- (void)viewWillAppear:(BOOL)animated{
	[[self navController] setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidAppear:(BOOL)animated{
	[[self navController] setToolbarHidden:YES animated:YES];
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	navController = nil;
	actionSheet = nil;
	weight = nil;
	speciesValue = nil;
	managedObjectContext = nil;
	location = nil;
	pickerView = nil;
	source = nil;
	currentPhoto = nil;
	mapView = nil;
}


- (void)dealloc {
    [super dealloc];
	[navController release];
	[actionSheet release];
	[weight release];
	[speciesValue release];
	[managedObjectContext release];
	[location release];
	[pickerView release];
	[source release];
	[currentPhoto release];
	[mapView release];
}


@end

